import {userLogoutUsingPost} from '@/services/backend/userController';
import {
    BellOutlined,
    GithubOutlined,
    LogoutOutlined,
    MoonOutlined,
    QuestionCircleOutlined,
    SunOutlined,
    UserOutlined,
} from '@ant-design/icons';
import {history, useModel} from '@umijs/max';
import {Avatar, Button, Row, Space, Switch} from 'antd';
import type {MenuInfo} from 'rc-menu/lib/interface';
import React, {useCallback} from 'react';
import {flushSync} from 'react-dom';
import {Link} from 'umi';
import HeaderDropdown from '../HeaderDropdown';
import {githubURL} from '@/constants';

export type GlobalHeaderRightProps = {
    menu?: boolean;
};

export const AvatarDropdown: React.FC<GlobalHeaderRightProps> = () => {
    /**
     * 退出登录，并且将当前的 url 保存
     */
    const loginOut = async () => {
        await userLogoutUsingPost();
        const urlParams = new URL(window.location.href).searchParams;
        /** 此方法会跳转到 redirect 参数所在的位置 */
        const redirect = urlParams.get('redirect');
        // Note: There may be security issues, please note
        if (window.location.pathname !== '/user/login' && !redirect) {
            history.replace({
                pathname: '/user/login',
                // search: stringify({
                //   redirect: pathname + search,
                // }),
            });
        }
    };

    const {initialState, setInitialState} = useModel('@@initialState');

    const onMenuClick = useCallback(
        (event: MenuInfo) => {
            const {key} = event;
            if (key === 'logout') {
                flushSync(() => {
                    setInitialState((s) => ({...s, currentUser: undefined}));
                });
                loginOut();
                return;
            }
            if (key === 'account') {
                history.push('/user/account');
                return;
            }
        },
        [setInitialState],
    );

    // 切换主题
    const toggleTheme = useCallback(
        (checked: boolean) => {
            flushSync(() => {
                setInitialState((s) => ({
                    ...s,
                    settings: {
                        ...s?.settings,
                        navTheme: checked ? 'realDark' : 'light',
                    },
                }));
            });

            // 存储主题偏好到本地存储
            // localStorage.setItem('theme', checked ? 'dark' : 'light');
        },
        [setInitialState],
    );

    const {currentUser, settings} = initialState || {};
    const isDarkTheme = settings?.navTheme === 'realDark';

    if (!currentUser) {
        return (
            <Link to="/user/login">
                <Button type="primary" shape="round">
                    登录
                </Button>
            </Link>
        );
    }

    const menuItems = [
        ...(currentUser
            ? [
                {
                    key: 'account',
                    icon: <UserOutlined/>,
                    label: '个人中心',
                },
                // {
                //   key: 'settings',
                //   icon: <SettingOutlined />,
                //   label: '个人设置',
                // },
                {
                    type: 'divider' as const,
                },
                {
                    key: 'theme',
                    label: (
                        <div style={{
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'space-between',
                            width: '100%'
                        }}>
                            <span>{isDarkTheme ? '深色模式' : '浅色模式'}</span>
                            <Switch
                                checked={isDarkTheme}
                                onChange={toggleTheme}
                                checkedChildren={<MoonOutlined/>}
                                unCheckedChildren={<SunOutlined/>}
                            />
                        </div>
                    ),
                },
            ]
            : []),
        {
            key: 'logout',
            icon: <LogoutOutlined/>,
            label: '退出登录',
        },
    ];

    const navIcon = () => (
        <>
            <BellOutlined
                style={{
                    fontSize: 20,
                    color: 'rgba(0, 0, 0, 0.65)',
                }}
            />
            <QuestionCircleOutlined
                style={{
                    fontSize: 20,
                    color: 'rgba(0, 0, 0, 0.65)',
                }}
            />
            <GithubOutlined
                style={{
                    fontSize: 20,
                    color: 'rgba(0, 0, 0, 0.65)',
                }}
                onClick={() => {
                    window.open(githubURL);
                }}
            />
        </>
    );

    return (
        <div>
            <Row justify="end" align="middle" style={{width: '100%', padding: '8px 16px'}}>
                <Space size={'middle'}>
                    {navIcon()}
                    <HeaderDropdown
                        menu={{
                            selectedKeys: [],
                            onClick: onMenuClick,
                            items: menuItems,
                        }}
                    >
                        <Space>
                            {currentUser?.avatarUrl ? (
                                <Avatar size="small" src={currentUser?.avatarUrl}/>
                            ) : (
                                <Avatar size="small" icon={<UserOutlined/>}/>
                            )}
                            <span>{currentUser?.userName ?? '无'}</span>
                        </Space>
                    </HeaderDropdown>
                </Space>
            </Row>
        </div>
    );
};